package com.guilin.system.service.impl;

import com.guilin.common.constant.CacheConstants;
import com.guilin.common.constant.UserConstants;
import com.guilin.common.core.redis.RedisCache;
import com.guilin.common.exception.ServiceException;
import com.guilin.common.exception.user.CaptchaException;
import com.guilin.common.exception.user.CaptchaExpireException;
import com.guilin.common.utils.DateUtils;
import com.guilin.common.utils.SecurityUtils;
import com.guilin.common.utils.StringUtils;
import com.guilin.domain.Alumni;
import com.guilin.dto.LoginDTO;
import com.guilin.mapper.AlumniMapper;
import com.guilin.system.service.AlumniLoginService;
import com.guilin.system.service.AlumniService;
import com.guilin.system.service.QQToKenService;
import com.guilin.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AlumniLoginServiceImpl implements AlumniLoginService {

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AlumniService alumniService;

    @Autowired
    private AlumniMapper alumniMapper;

    @Autowired
    private QQToKenService qqtokenService;

    public String login(LoginDTO loginDTO){

        //1.校验验证码是否正确
        verifyValidateCaptcha(loginDTO.getCode(), loginDTO.getUuid());

        //2.获取登录标识并查询校友信息
        Alumni alumni = getLoginIdentifier(loginDTO);
        System.out.println("查询到的Alumni对象: " + alumni);
        System.out.println("accountStatus: " + alumni.getAccountStatus());
        System.out.println("所有属性: " + alumni.toString());

        //3.查询校友信息
//        Alumni alumni = findAlumniByIdentifier(identifier);

        //4.校验密码是否正确
        if(alumni == null || !SecurityUtils.matchesPassword(loginDTO.getPassword(), alumni.getPassword())){

            throw new ServiceException("账号或者密码错误");
        }

        //5.校验账号是否被禁用
        if(!UserConstants.ALUMNI_ACCOUNT_STATUS_ENABLE.equals(alumni.getAccountStatus())){
            System.out.println("数据库获取的账号状态: " + alumni.getAccountStatus());
            System.out.println("状态值类型: " + alumni.getAccountStatus().getClass());
            System.out.println("比较结果: " + UserConstants.ALUMNI_ACCOUNT_STATUS_ENABLE.equals(alumni.getAccountStatus()));

            throw new ServiceException("账号已被禁用");
        }

        //6.记录当前登录时间
        alumni.setLastLoginTime(DateUtils.getNowDate());
        alumniMapper.updateAlumni(alumni);

        //7.生成令牌

        return qqtokenService.createToken(alumni);
    }


    public void verifyValidateCaptcha(String code, String uuid){

        //1.判断验证码功能是否启用
        if(!configService.selectCaptchaEnabled()){

            //未启用，直接放行
            return;
        }

        //2.验证码校验
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(uuid)){
            throw new ServiceException("验证码不能为空");
        }

        //3.构建redis缓存键
        //String redisKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String redisKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");

        //4.从redis中获取验证码
        String captchaCode = redisCache.getCacheObject(redisKey);

        //5.校验验证码是否正确
        if(captchaCode == null){
            //验证码失效
            throw new CaptchaExpireException();
        }

        //7.校验验证码是否正确(忽略大小写)
        if(!code.equalsIgnoreCase(captchaCode)){

            // 错误计数
            incrementCaptchaErrorCount(uuid);
            throw new CaptchaException();
        }

        // 7. 验证通过后删除缓存，防止重复使用
        redisCache.deleteObject(redisKey);

        // 8. 清除错误计数
        clearCaptchaErrorCount(uuid);

    }

    /**
     * 增加验证码错误计数
     */
    private void incrementCaptchaErrorCount(String uuid) {
        String errorKey = CacheConstants.CAPTCHA_CODE_KEY + "error:" + uuid;
        Integer errorCount = redisCache.getCacheObject(errorKey);

        if (errorCount == null) {
            // 初始化为1，设置10分钟过期
            redisCache.setCacheObject(errorKey, "1", 10, TimeUnit.MINUTES);
        } else if (errorCount >= 3) {
            // 错误次数过多，删除验证码
            redisCache.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
            throw new CaptchaExpireException();
        } else {
            redisCache.incrementObject(errorKey);
        }
    }

    /**
     * 清除验证码错误计数
     */
    private void clearCaptchaErrorCount(String uuid) {
        redisCache.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + "error:" + uuid);
    }


    //获取登录标识
    public Alumni getLoginIdentifier(LoginDTO loginDTO){

        //判断登录方式
        if(!StringUtils.isEmpty(loginDTO.getUsername())){
            return alumniMapper.selectAlumniByUsername(loginDTO.getUsername());
        }else if(!StringUtils.isEmpty(loginDTO.getPhone())){
            return alumniMapper.selectAlumniByPhone(loginDTO.getPhone());
        }else if(!StringUtils.isEmpty(loginDTO.getEmail())){
            return alumniMapper.selectAlumniByEmail(loginDTO.getEmail());
        }else {
            throw new ServiceException("请输入用户名、手机号或邮箱");
        }

    }
//
//    //根据登录标识查询校友信息
//    public Alumni findAlumniByIdentifier(String identifier){
//        //查询数据库
//        return alumniMapper.selectAlumniByUsername(identifier);
//    }

}
